﻿using System.Linq;
using MRGSP.SurveyMaster.Core;
using MRGSP.SurveyMaster.Core.Model;
using MRGSP.SurveyMaster.Core.Repository;
using MRGSP.SurveyMaster.Core.Service;

namespace MRGSP.SurveyMaster.Service.Services
{
    public class UserService : IUserService
    {
        private readonly IRepo<User> userRepo;

        public UserService(IRepo<User> userRepo)
        {
            this.userRepo = userRepo;
        }

        public IPageable<User> GetPage(int page, int pageSize)
        {
            return userRepo.GetPageable(page, pageSize);
        }

        public long Create(User user)
        {
            return userRepo.Insert(user);
        }

        public long Save(User user)
        {
            return userRepo.Update(user);
        }

        public void Delete(long id)
        {
            userRepo.Delete(id);
        }

        public User Get(long id)
        {
            return userRepo.Get(id);
        }

        public User Get(string login)
        {
            return userRepo.GetWhere(new { login }).SingleOrDefault();
        }

        public bool Exists(string login)
        {
            return userRepo.CountWhere(new{login}).Equals(1);
        }

        public bool Exists(string login, string password)
        {
            return userRepo.CountWhere(new{login, password}).Equals(1);
        }

        public string GetRole(string login)
        {
            var user = userRepo.GetWhere(new {login}).Single();
            if (user.Role == 1) return The.Admin;
            return user.Role == 2 ? The.User : string.Empty;
        }

    }
}